package com.fram.common.util.jpush;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.fram.common.canstant.ErrCode;
import com.fram.common.canstant.PublicConstant;
import com.fram.common.enums.PayCodeEnum;
import com.fram.common.exception.ProAffairException;
import com.fram.common.exception.ProRunTimeException;
import com.fram.common.util.json.JSONTools;
import com.fram.entity.MessageData;
import com.fram.entity.User;
import com.fram.mapper.MessageDataMapper;
import com.fram.mapper.UserMapper;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;

/**
 * @作者： 陳曉鬆 @时间： 2020年10月20日 - 下午2:59:01 @description：->
 */
@Component
public class JpushUtils {

	private static Logger LOG = LoggerFactory.getLogger(JpushUtils.class);

	private static String masterSecret = "b54583c49bc19fbc6b9ee92d";
	private static String appKey = "bdbf07a363cf302b9b3c6ecc";

	@Autowired
	private UserMapper userMaper;
	@Autowired
	private MessageDataMapper messageDataMapper;

	public void sendJpush(MessageData request) throws ProAffairException {
		if (StringUtils.isEmpty(request.getTitle())) {
			request.setTitle("通知消息");
		}
		if (StringUtils.isEmpty(request.getMessage())) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), "没有通知内容");
		}
		JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());
		PushPayload payload = null;
		User user = null;
		if (request.getReceiveUserId() == null || request.getReceiveUserId() == 0) {
			payload = PushPayload.alertAll(request.getMessage());
		} else {
			user = userMaper.selectByPrimaryKey(request.getReceiveUserId());
			if (user == null || StringUtils.isEmpty(user.getRegistrationId()) || !user.getRegistrationId().contains("_")) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "没有该用户信息");
			}
			Map<String, String> map = new HashMap<String, String>();
			if (!StringUtils.isEmpty(request.getJumpParam())) {
				map.put("jumpParam", request.getJumpParam());
			}
			String[] str = user.getRegistrationId().split("_");
			if (PayCodeEnum.SOURCE_4.getType() == Integer.valueOf(str[1])) {// 苹果
				payload = PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.registrationId(str[0]))
						.setNotification(Notification.ios(request.getMessage(), map)).build();

			}
			if (PayCodeEnum.SOURCE_5.getType() == Integer.valueOf(str[1])) {// 安卓
				payload = PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.registrationId(str[0]))
						.setNotification(Notification.android(request.getMessage(), request.getTitle(), map)).build();
			}
		}
		try {
			PushResult result = jpushClient.sendPush(payload);
			LOG.info("-jpush-Got result - " + result);
			if (0 != result.statusCode) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "发送信息失败");
			}
			// 记录到表
			request.setType(PublicConstant.MESSAGE_TYPE_3);
			if (messageDataMapper.insertSelective(request) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "消息发送成功，入库失败");
			}
		} catch (APIConnectionException e) {
			LOG.error("-jpush-参数：" + JSONTools.obj2json(request) + "-Connection error, should retry later:" + e);
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "Connection error, should retry later");
		} catch (APIRequestException e) {
			LOG.error("-jpush-参数：" + JSONTools.obj2json(request) + "-Should review the error, and fix the request:" + e);
			LOG.error("-jpush-参数：" + JSONTools.obj2json(request) + "-HTTP Status: " + e.getStatus());
			LOG.error("-jpush-参数：" + JSONTools.obj2json(request) + "-Error Code: " + e.getErrorCode());
			LOG.error("-jpush-参数：" + JSONTools.obj2json(request) + "-Error Message: " + e.getErrorMessage());
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "Should review the error, and fix the request");
		}
	}

	public static void main(String[] args) {
		JPushClient jpushClient = new JPushClient("b54583c49bc19fbc6b9ee92d", "bdbf07a363cf302b9b3c6ecc", null, ClientConfig.getInstance());
		Map<String, String> map = new HashMap<String, String>();
		map.put("jumpParam", "{\"resType\":6,\"resId\":1}");
		PushPayload payload = PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.registrationId("120c83f760ad95dee30"))
				.setNotification(Notification.android("我是标题", "我是内容", map)).build();
		try {
			PushResult result = jpushClient.sendPush(payload);
			System.out.println("Got result - " + result);
		} catch (APIConnectionException e) {
			// Connection error, should retry later
			System.out.println("Connection error, should retry later" + e);
		} catch (APIRequestException e) {
			// Should review the error, and fix the request
			System.out.println("Should review the error, and fix the request" + e);
			System.out.println("HTTP Status: " + e.getStatus());
			System.out.println("Error Code: " + e.getErrorCode());
			System.out.println("Error Message: " + e.getErrorMessage());
		}
	}

}
